package com.leyou.auth.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.auth.config.AliOssProperties;
import com.leyou.auth.dto.AliOssSignatureDTO;
import com.leyou.auth.service.AliAuthService;
import lombok.extern.slf4j.Slf4j;



import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Slf4j
public class AliAuthServiceImpl implements AliAuthService {
    @Resource
    private AliOssProperties prop;
    @Resource
    private OSS client;

    @Override
    public AliOssSignatureDTO getAliSignature() {
        try {
            // 1.计算过期时间
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime;
            Date expiration = new Date(expireEndTime);

            // 2.设置上传策略
            PolicyConditions policyConds = new PolicyConditions();
            // 2.1.文件大小限制
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            // 2.2.上传目录
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            // 2.3.生成策略
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            // 2.4.编码
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 3.生成签名
            String postSignature = client.calculatePostSignature(postPolicy);


            //设置回调参数
            JSONObject jasonCallback = new JSONObject();
            jasonCallback.put("callbackUrl", prop.getCallbackUrl());
            jasonCallback.put("callbackBody","filename=${object}&size=${size}&mimeType=${mimeType}");
            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
            String callbackBase = BinaryUtil.toBase64String(JSONObject.toJSONString(jasonCallback).getBytes());
            client.shutdown();

            // 4.封装要返回的结果
            return AliOssSignatureDTO.of(prop.getAccessKeyId(), prop.getHost(), encodedPolicy, postSignature, expireEndTime, prop.getDir(),callbackBase);
            //return AliOssSignatureDTO.of(prop.getAccessKeyId(), prop.getHost(), encodedPolicy, postSignature, expireEndTime, prop.getDir());
        } catch (Exception e) {
            client.shutdown();
            log.error("上传文件失败，原因：{}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败！", e);
        }


    }

    public void deleteFile(String filename) {
        String bucketName = prop.getBucketName();
        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        client.deleteObject(bucketName, filename);
        // 关闭OSSClient。
        client.shutdown();
    }
}
